/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package vista;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Toolkit;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import modelo.Indice;
import modelo.Tabla;
import modelo.Tablespace;
import modelo.conexion.RecolectorDatos;
import modelo.persistencia.XML;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.NumberTickUnit;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.IntervalMarker;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.CategoryItemRenderer;
import org.jfree.chart.renderer.category.LineRenderer3D;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.ui.Layer;
import org.jfree.ui.RectangleAnchor;
import org.jfree.ui.TextAnchor;

/**
 *
 * @author Andrés
 */
public class VistaPrincipalCpu extends javax.swing.JFrame {

    /**
     * Creates new form VistaPrincipalCpu
     */
    private JFreeChart grafMem;
    private DefaultCategoryDataset datasetMem;
    private ArrayList<Double> prctjMem;
    private JFreeChart grafCpu;
    private DefaultCategoryDataset datasetCpu;
    private ArrayList<Double> prctjCpu;
    private DefaultTableModel defaultTableModel;
    private IntervalMarker target;
    private int ain;
    private int bin;
    private RecolectorDatos recolectorDatos;
    private XML objXML;

    public void setRecolectorDatos(RecolectorDatos recolectorDatos) {
        this.recolectorDatos = recolectorDatos;
    }
    
    public VistaPrincipalCpu() {
        initComponents();
        inicializarVariables();
        setVisible(false);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setResizable(false);
        iniciarLogo();
    }

    public final void inicializarVariables() {
        objXML  = new XML();
        recolectorDatos = new RecolectorDatos();
        datasetMem = new DefaultCategoryDataset();
        prctjMem = new ArrayList<>();
        datasetCpu = new DefaultCategoryDataset();
        prctjCpu = new ArrayList<>();
        this.defaultTableModel = new DefaultTableModel();
        defaultTableModel = (DefaultTableModel) tablaIndices.getModel();
        this.ain = 49;
        this.bin = 51;
    }

    public final void iniciarLogo() {
        setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("./image/logo.png")));
    }

    public void agregarListenerItemCerrar(ActionListener actionListener) {
        this.itemCerrar.addActionListener(actionListener);
    }

    public void agregarListenerItemAcerdaDe(ActionListener actionListener) {
        this.itemAcercaDe.addActionListener(actionListener);
    }

    public void agregarListenerItemCambiarMonitor(ActionListener actionListener) {
        this.itemMonitores.addActionListener(actionListener);
    }

    public void agregarListenerBotonDesfragmentar(ActionListener actionListener) {
        this.botonDesfragmenta.addActionListener(actionListener);
    }

    public void pintarGrafMemoria(String prct) {
        if (prctjMem.size() == 10) {
            prctjMem.remove(0);
        }
        prctjMem.add(Double.valueOf(prct) / 1000);
        for (int j = 0; j < prctjMem.size(); j++) {
            datasetMem.addValue(prctjMem.get(j), "", String.valueOf(j));
        }
        grafMem = ChartFactory.createLineChart("", "", "", datasetMem, PlotOrientation.VERTICAL, true, true, false);
        CategoryPlot plot = (CategoryPlot) grafMem.getPlot();
        plot.getRenderer().setSeriesStroke(0, new BasicStroke(3));
        plot.getRenderer().setSeriesPaint(0, new java.awt.Color(47, 109, 16));
        plot.getRenderer().setBaseOutlineStroke(new BasicStroke(3));
        plot.getRenderer().setSeriesVisibleInLegend(0, false);
        CategoryItemRenderer renderer = plot.getRenderer();
        renderer.setSeriesItemLabelsVisible(10, false);

        grafMem.setBackgroundPaint(new Color(255, 255, 255, 0));
        grafMem.setBorderVisible(false);
        CategoryPlot cPlot = grafMem.getCategoryPlot();
        cPlot.setBackgroundPaint(new Color(255, 255, 255, 0));
        cPlot.setBackgroundAlpha(0.0f);
        cPlot.setDomainGridlinePaint(Color.white);
        cPlot.setDomainGridlinesVisible(false);
        cPlot.setRangeGridlinePaint(Color.white);
        cPlot.setOutlineVisible(false);


        // set the range axis to display integers only...
        final NumberAxis rangeAxis = (NumberAxis) cPlot.getRangeAxis();
        rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
        //rangeAxis.setVisible(false);

        CategoryAxis domainAxis = cPlot.getDomainAxis();
        domainAxis.setCategoryLabelPositions(
                CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 6.0));
        BufferedImage graficoTorta = grafMem.createBufferedImage(324, 178);
        graficoMem.setIcon(new ImageIcon(graficoTorta));
        this.repaint();
    }

    public void pintarGrafCpu(Double prct) throws SQLException {
        if (prctjCpu.size() == 10) {
            prctjCpu.remove(0);
        }

        if ((prct * 100) > (int) spinnerUmbral.getValue()) {
            sobrepasaLimites();
        }

        prctjCpu.add(prct * 100);//*100 quitar, solo para prueba
        for (int j = 0; j < prctjCpu.size(); j++) {
            datasetCpu.addValue(prctjCpu.get(j), "", String.valueOf(j));
        }
        grafCpu = ChartFactory.createLineChart("", "", "", datasetCpu, PlotOrientation.VERTICAL, true, true, false);
        CategoryPlot plot = (CategoryPlot) grafCpu.getPlot();
        plot.getRenderer().setSeriesStroke(0, new BasicStroke(3));
        plot.getRenderer().setSeriesPaint(0, new java.awt.Color(47, 109, 16));
        plot.getRenderer().setBaseOutlineStroke(new BasicStroke(3));
        plot.getRenderer().setSeriesVisibleInLegend(0, false);
        CategoryItemRenderer renderer = plot.getRenderer();
        renderer.setSeriesItemLabelsVisible(10, false);

        grafCpu.setBackgroundPaint(new Color(255, 255, 255, 0));
        grafCpu.setBorderVisible(false);
        CategoryPlot cPlot = grafCpu.getCategoryPlot();
        cPlot.setBackgroundPaint(new Color(255, 255, 255, 0));
        cPlot.setBackgroundAlpha(0.0f);
        cPlot.setDomainGridlinePaint(Color.white);
        cPlot.setDomainGridlinesVisible(false);
        cPlot.setRangeGridlinePaint(Color.white);
        cPlot.setOutlineVisible(false);


        // set the range axis to display integers only...
        final NumberAxis rangeAxis = (NumberAxis) cPlot.getRangeAxis();
        rangeAxis.setRange(0.00, 100.00);
        rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

        target = new IntervalMarker(ain, bin);
        target.setLabelFont(new Font("SansSerif", Font.ITALIC, 11));
        target.setLabelAnchor(RectangleAnchor.LEFT);
        target.setLabelTextAnchor(TextAnchor.CENTER_LEFT);
        target.setPaint(Color.red);
        cPlot.addRangeMarker(target, Layer.BACKGROUND);

        CategoryAxis domainAxis = cPlot.getDomainAxis();
        domainAxis.setCategoryLabelPositions(
                CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 6.0));
        BufferedImage graficoTorta = grafCpu.createBufferedImage(324, 178);
        graficoCpu.setIcon(new ImageIcon(graficoTorta));
        this.repaint();
    }

    public void sobrepasaLimites() throws SQLException {
        JOptionPane.showMessageDialog(null, "Ha sobrepasado los limites del umbral");
        List<String> ccc = recolectorDatos.ultimasConsultas();
        objXML.Escribir_XML_Consulta(ccc);
    }

    public void agregarInfoIndices(ArrayList<Indice> indices) {
        if (defaultTableModel.getRowCount() > 0) {
            for (int i = defaultTableModel.getRowCount() - 1; i > -1; i--) {
                defaultTableModel.removeRow(i);
            }
        }
        for (Indice ind : indices) {
            if (ind.getFragmentacion() > 0) {
                defaultTableModel.addRow(new Object[]{ind.getNombre(), ind.getOwner(), ind.getFragmentacion()});
            }
        }
        tablaIndices.repaint();

        this.repaint();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        graficoCpu = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        graficoMem = new javax.swing.JLabel();
        panelIndices = new javax.swing.JScrollPane();
        tablaIndices = new javax.swing.JTable();
        botonDesfragmenta = new javax.swing.JButton();
        spinnerUmbral = new javax.swing.JSpinner();
        labelSpinner = new javax.swing.JLabel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        itemMonitores = new javax.swing.JMenuItem();
        itemCerrar = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        itemAcercaDe = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Monitor Administracion Bases de Datos");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)), "CPU"));

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(graficoCpu, javax.swing.GroupLayout.DEFAULT_SIZE, 324, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(graficoCpu, javax.swing.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE)
                .addContainerGap())
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)), "Memoria"));

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(graficoMem, javax.swing.GroupLayout.DEFAULT_SIZE, 324, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(graficoMem, javax.swing.GroupLayout.DEFAULT_SIZE, 178, Short.MAX_VALUE)
                .addContainerGap())
        );

        panelIndices.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)), "Indices"));

        tablaIndices.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Indice", "Owner", "% Fragmentacion"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        panelIndices.setViewportView(tablaIndices);

        botonDesfragmenta.setText("Desfragmentar");

        spinnerUmbral.setModel(new javax.swing.SpinnerNumberModel(50, 1, 100, 1));
        spinnerUmbral.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                spinnerUmbralStateChanged(evt);
            }
        });

        labelSpinner.setText("Modifica Umbral:");

        jMenu1.setText("Archivo");

        itemMonitores.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_M, java.awt.event.InputEvent.CTRL_MASK));
        itemMonitores.setText("Cambiar Monitor");
        jMenu1.add(itemMonitores);

        itemCerrar.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.CTRL_MASK));
        itemCerrar.setText("Cerrar");
        jMenu1.add(itemCerrar);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Ayuda");

        itemAcercaDe.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_H, java.awt.event.InputEvent.CTRL_MASK));
        itemAcercaDe.setText("Acerca de");
        jMenu2.add(itemAcercaDe);

        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(panelIndices, javax.swing.GroupLayout.PREFERRED_SIZE, 401, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(botonDesfragmenta, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(114, 114, 114)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(labelSpinner)
                        .addGap(18, 18, 18)
                        .addComponent(spinnerUmbral, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(31, 31, 31))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(panelIndices, javax.swing.GroupLayout.PREFERRED_SIZE, 421, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(botonDesfragmenta, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(spinnerUmbral, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(labelSpinner))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(19, 19, 19))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void spinnerUmbralStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_spinnerUmbralStateChanged
        int valor = (int) spinnerUmbral.getValue();
        ain = valor - 1;
        bin = valor + 1;
    }//GEN-LAST:event_spinnerUmbralStateChanged

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(VistaPrincipalCpu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(VistaPrincipalCpu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(VistaPrincipalCpu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(VistaPrincipalCpu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new VistaPrincipalCpu().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botonDesfragmenta;
    private javax.swing.JLabel graficoCpu;
    private javax.swing.JLabel graficoMem;
    private javax.swing.JMenuItem itemAcercaDe;
    private javax.swing.JMenuItem itemCerrar;
    private javax.swing.JMenuItem itemMonitores;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JLabel labelSpinner;
    private javax.swing.JScrollPane panelIndices;
    private javax.swing.JSpinner spinnerUmbral;
    private javax.swing.JTable tablaIndices;
    // End of variables declaration//GEN-END:variables
}
